#include <iostream>
#include <string>
#include <functional>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <cstring>
#include <sys/wait.h>
#include <pthread.h>

#include "ThreadPool.hpp"
#include "InetAddr.hpp"
#include "Log.hpp"

enum
{
    SOCKET_ERROR = 1,
    BIND_ERROR,
    LISTEN_ERROR,
    USAGE_ERROR
};

const static int defaultsockfd = -1;
const static int gbacklog = 16;

// 声明
class TcpServer;

class ThreadData
{
public:
    ThreadData(int fd, InetAddr addr, TcpServer *s)
        : sockfd(fd), clientaddr(addr), self(s)
    {
    }

public:
    int sockfd;
    InetAddr clientaddr;
    TcpServer *self;
};

using task_t = std::function<void()>;

class TcpServer
{
public:
    TcpServer(int port)
        : _port(port), _listensock(defaultsockfd), _isrunning(false)
    {
    }

    void InitServer()
    {
        // 1 创建套接字
        // tcp
        _listensock = ::socket(AF_INET, SOCK_STREAM, 0);

        if (_listensock < 0)
        {
            LOG(ERROR, "socket error");
            exit(1);
        }
        LOG(DEBUG, "socket success,socketfd is : %d\n", _listensock);

        // 2 bind
        struct sockaddr_in local;
        memset(&local, 0, sizeof(local));
        local.sin_family = AF_INET;
        local.sin_port = htons(_port);
        local.sin_addr.s_addr = INADDR_ANY;

        int n = ::bind(_listensock, (struct sockaddr *)&local, sizeof(local));

        if (n < 0)
        {
            LOG(FATAL, "bind error");
            exit(2);
        }
        LOG(DEBUG, "bind success, socketfd is : %d\n", _listensock);

        // 3 先建立连接
        // tcpserver 启动 一直等待client连接
        n = ::listen(_listensock, gbacklog);

        if (n < 0)
        {
            LOG(FATAL, "listen error");
            exit(LISTEN_ERROR);
        }

        LOG(DEBUG, "listen success, socketfd is : %d\n", _listensock);
    }

    void Service(int sockfd, InetAddr client)
    {
        LOG(DEBUG, "get a new link , info %s:%d , fd:%d\n", client.GetIp().c_str(), client.GetPort(), sockfd);

        std::string clientaddr = "[" + client.GetIp() + ":" + std::to_string(client.GetPort()) + "]#";

        while (true)
        {
            char buffer[1024];
            ssize_t n = read(sockfd, buffer, sizeof(buffer) - 1);

            if (n > 0)
            {
                buffer[n] = 0;
                std::cout << clientaddr << buffer << std::endl;

                // 发回一样的消息
                std::string echo_string = "[server echo]#";
                echo_string += buffer;

                write(sockfd, echo_string.c_str(), echo_string.size());
            }
            else if (n == 0)
            {
                // client 退出&&关闭连接
                LOG(INFO, "%s quit\n", clientaddr.c_str());
                break;
            }
            else
            {
                LOG(ERROR, "read error\n");
                break;
            }
        }

        std::cout << "server 开始退出" << std::endl;
        // 关闭读
        shutdown(sockfd, SHUT_RDWR);
        std::cout << "shut_rd" << std::endl;
        sleep(5);
    }

    static void *ThreadFunc(void *args)
    {

        pthread_detach(pthread_self());
        ThreadData *data = static_cast<ThreadData *>(args);
        data->self->Service(data->sockfd, data->clientaddr);
        delete data;
        return nullptr;
    }

    void Loop()
    {
        _isrunning = true;
        // 4 不能直接接受数据，先获取连接
        while (_isrunning)
        {
            struct sockaddr_in peer;
            socklen_t len = sizeof(peer);
            // 接受一个连接请求
            int sockfd = accept(_listensock, (struct sockaddr *)&peer, &len);

            if (sockfd < 0)
            {
                LOG(FATAL, "accept error\n");
                continue;
            }

            // version 0 一次处理一个请求---开玩笑
            // Service(sockfd, InetAddr(peer));

            // version 1 : 多进程处理请求
            // pid_t pid = fork();
            // if (pid == 0)
            // {
            //     // child
            //     // 关心socketfd 不关心listensock
            //     ::close(_listensock); // 建议

            //     if (fork() > 0)
            //         exit(0);
            //     // 孙子进程--孤儿--系统管
            //     Service(sockfd, InetAddr(peer));
            //     exit(0);
            // }s

            // // father
            // // 不关心socketfd 关心listensock
            // ::close(sockfd);
            // waitpid(pid, nullptr, 0);

            // version 2:多线程
            // pthread_t t;
            // ThreadData *data = new ThreadData(sockfd, InetAddr(peer), this);
            // // data是传给(void*)ThreadFunc的参数
            // pthread_create(&t, nullptr, ThreadFunc, data); // 线程分离

            //version 3:线程池
            task_t t=std::bind(&TcpServer::Service, this, sockfd, InetAddr(peer));
            ThreadPool<task_t>::GetInstance()->Enqueue(t);
        }
        _isrunning = false;
    }

    ~TcpServer()
    {
        if (_listensock > defaultsockfd)
            ::close(_listensock);
    }

private:
    uint16_t _port;
    int _listensock; // 监听套接字
    bool _isrunning;
};
